const { querySql, queryOne } = require('../utils/index');
const { body, validationResult } = require('express-validator');
const boom = require('boom');
const jwt = require('jsonwebtoken');
const md5 = require('../utils/md5');
const {
  CODE_ERROR,
  CODE_SUCCESS,
  PRIVATE_KEY,
  JWT_EXPIRED,
  APPID,
  SECRETID,
  SECRETKRY
} = require('../utils/constant');
// 登录
function login (req, res, next) {
  const err = validationResult(req);
  // 如果验证错误，empty不为空
  if (!err.isEmpty()) {
    // 获取错误信息
    const [{ msg }] = err.errors;
    // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回
    next(boom.badRequest(msg));
  } else {
    let { userid, password } = req.body;
    console.log(userid, password)
    // md5加密
    // password = md5(password);
    const query = `select * from admin where userid='${userid}' and password='${password}'`;
    querySql(query)
      .then(user => {
        console.log('用户登录===', user);
        if (!user || user.length === 0) {
          res.json({
            code: CODE_ERROR,
            msg: '用户名或密码错误',
            data: null
          })
        } else {
          // 登录成功，签发一个token并返回给前端
          const token = jwt.sign(
            // payload：签发的 token 里面要包含的一些数据。
            { userid },
            // 私钥
            PRIVATE_KEY,
            // 设置过期时间
            { expiresIn: JWT_EXPIRED }
          )

          let userData = {
            id: user[0].id,
            username: user[0].username,
            nickname: user[0].nickname,
            avator: user[0].avator,
            sex: user[0].sex,
            gmt_create: user[0].gmt_create,
            gmt_modify: user[0].gmt_modify
          };

          res.json({
            code: CODE_SUCCESS,
            msg: '登录成功',
            data: {
              token,
              userData
            }
          })
        }
      })
  }
}
// 注册
function register (req, res, next) {
  const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
  } else {
    let { userid, password, nickname, avatar, phone, address } = req.body;
    findUser(userid)
      .then(data => {
        console.log('用户注册===', data);
        if (data) {
          res.json({
            code: CODE_ERROR,
            msg: '用户已存在',
            data: null
          })
        } else {
          // password = md5(password);
          const query = `insert into admin(userid, password ,nickname, avatar, phone, address) values('${userid}', '${password}' , '${nickname}' , '${avatar}' , '${phone}' , '${address}')`;
          querySql(query)
            .then(result => {
              // console.log('用户注册===', result);
              if (!result || result.length === 0) {
                res.json({
                  code: CODE_ERROR,
                  msg: '注册失败',
                  data: null
                })
              } else {
                const queryUser = `select * from admin where userid='${userid}' and password='${password}'`;
                querySql(queryUser)
                  .then(user => {
                    const token = jwt.sign(
                      { userid },
                      PRIVATE_KEY,
                      { expiresIn: JWT_EXPIRED }
                    )

                    let userData = {
                      id: user[0].id,
                      username: user[0].username,
                      nickname: user[0].nickname,
                      avator: user[0].avator,
                      sex: user[0].sex,
                      gmt_create: user[0].gmt_create,
                      gmt_modify: user[0].gmt_modify
                    };

                    res.json({
                      code: CODE_SUCCESS,
                      msg: '注册成功',
                      data: {
                        token,
                        userData
                      }
                    })
                  })
              }
            })
        }
      })

  }
}

//微信小程序登录
function loginWX (req, res, next) {
  // console.log(req.body)
  let { code } = req.body;//获取小程序传来的code
  // let encryptedData = params.encryptedData;//获取小程序传来的encryptedData
  // let iv = req.iv;//获取小程序传来的iv
  let appid = "wx6f56872bcb123187";//自己小程序后台管理的appid，可登录小程序后台查看
  let secret = "62757e48effb00679e15e24057bb454d";//小程序后台管理的secret，可登录小程序后台查看
  //特种设备
  //   let appid = "wx4cd4044d982e8292";//自己小程序后台管理的appid，可登录小程序后台查看
  // let secret = "18aed44256089d00d7cbcbda14efc39c";//小程序后台管理的secret，可登录小程序后台查看
  let grant_type = "authorization_code";// 授权（必填）默认值
  //请求获取openid
  let url = "https://api.weixin.qq.com/sns/jscode2session?grant_type=" + grant_type + "&appid=" + appid + "&secret=" + secret + "&js_code=" + code;

  let openid, sessionKey;

  let https = require("https");
  console.log(code)
  https.get(url, (res1) => {
    // console.log(res1)
    // res.json({
    //   openid: res1.openid
    // })
    res1.on('data', (d) => {
      console.log('返回的信息: ', JSON.parse(d));
      res.json(JSON.parse(d))
      openid = JSON.parse(d).openid;//得到openid
      sessionKey = JSON.parse(d).session_key;//得到session_key

    }).on('error', (e) => {
      console.error(e);
    });
  });
}

//查询userid信息
function getUserIdInfo (req, res, next) {
  let { userid } = req.body;
  findUser(userid).then(data => {
    // console.log('用户注册===', data);
    if (data) {
      res.json({
        code: CODE_SUCCESS,
        msg: '用户已存在',
        data: data
      })
    } else {
      res.json({
        code: CODE_ERROR,
        msg: '查询不到该用户',
        data: false
      })
    }
  })
}
// 校验用户名和密码
function validateUser (username, oldPassword) {
  const query = `select id, username from sys_user where username='${username}' and password='${oldPassword}'`;
  return queryOne(query);
}

// 通过用户名查询用户信息
function findUser (userid) {
  const query = `select * from admin where userid='${userid}'`;
  return queryOne(query);
}

module.exports = {
  register,
  login,
  loginWX,
  getUserIdInfo
}